package com.htbb.common.util;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * xml与javaObj转换工具类（使用jaxb）
 * @author lll
 * @date 2017年8月18日11:22:37
 */
public class JaxbXmlUtil {
	private static final Logger logger = LoggerFactory.getLogger(JaxbXmlUtil.class);
	
	
	/**
	 * JavaBean转换成xml
	 * @param obj 要转换的javaObj
	 * @param otherClasses obj中泛型的具体类，没有则传null
	 * @return xml字符串
	 */
	public static String convertObjectToXml(Object obj, Class<?>... otherClasses) {
		Class<?>[] classes = new Class<?>[1 + (otherClasses == null ? 0 : otherClasses.length)];
		classes[0] = obj.getClass();
		for (int i = 1; i < classes.length; ++i){
			classes[i] = otherClasses[i - 1];
		}
		String xmlStr = null;
		try{
			JAXBContext context = JAXBContext.newInstance(classes);    // 获取上下文对象  
	        Marshaller marshaller = context.createMarshaller(); // 根据上下文获取marshaller对象  
	          
	        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");  // 设置编码字符集  
	        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // 格式化XML输出，有分行和缩进  
	          
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
	        marshaller.marshal(obj, baos);  
	        xmlStr = new String(baos.toByteArray());         // 生成XML字符串    
		} catch(JAXBException e){
			logger.error("javaObj转换xml异常：", e);
		}
        return xmlStr;
	}
	
	/** 
     * xml转换成JavaBean 
     * @param xml
     * @param targetClass 转换的目标类
     * @return 目标对象
     */  
    public static <T> T convertXmlToObject(String xml, Class<T> targetClass) {  
    	T t = null;  
        try {  
            JAXBContext context = JAXBContext.newInstance(targetClass);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            StringReader sReader = new StringReader(xml);
            t = (T) unmarshaller.unmarshal(sReader);
        } catch (Exception e) {  
        	logger.error("xml转换javaObj异常：", e);
        }  
  
        return t;  
    }  
}
